//
// Created by kenny on 25-10-21.
// MCP 主API 服务
//
#include "mcp_service.h"

#include "mcp_net_mgr.h"
#include "mcp_logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mcp_json.h"
#include "mcp_decode.h"
#include "mcp_encrypt.h"
#include "mcp_retry_send.h"
#include "mcp_recv_mgr.h"
#include <stdatomic.h>
#include "mcp_cmap.h"
#include "mcp_exception.h"
#include "platform/comm_timer.h"
#include "mcp_decode.h"

// 网络连接管理
mcp_net_t net_mgr;
// 重发管理器
mcp_retry_manager_t retry_manager;
// 数据包处理器
packet_processor_t* packet_processor = NULL;

static void event_recv_msg(const char* message, uint8_t response_protocol, uint16_t response_sequence);
static void static_push_data(const uint8_t* data, uint16_t length, uint16_t sequence);

typedef struct {
    char server_ip[16];
    int server_port;
    char device_id[32];
    char name[32];
    int interval;
    uint8_t version;
    uint8_t encrypt;
    volatile bool is_running;
    volatile bool is_connected;

    connection_type_t socket_type;
    on_register_success on_register_success;

    on_register_failure on_register_failure;
    on_unregister on_unregister;
    on_cmd_success on_cmd_success;
    on_cmd_timeout on_cmd_timeout;
    on_async_response on_async_response;
    on_connection_status on_connection_status;
    on_get_device_info on_get_device_info;
    on_get_position on_get_position;
    on_server_time on_server_time;
} config_data_t;

config_data_t config_data = {
    .server_ip = "127.0.0.1",
    .server_port = 18362,
    .name = "测试机器",
    .interval = 30,
    .version = 0x01,
    .encrypt = 0x01,
    .is_running = false,
    .is_connected = false,
    .socket_type = CONNECTION_TYPE_TCP
};

// 心跳数据
typedef struct {
    char device_id[32];
    int sequence;
} heartbeat_data_t;
heartbeat_data_t heartbeat_data = {
    .device_id = "300281",
    .sequence = 0
};

int is_string_empty(const char* str) {
    return (str == NULL || str[0] == '\0');
}

//========================== 心跳定时器 ===========================
static void my_heartbeat_function(const void* user_data);
comm_timer_t* timer_heartbeat=NULL;
timer_config_t timer_config_heartbeat = {
    .enabled = true,
    .interval_sec = 3,  // 3秒间隔
    .user_func = my_heartbeat_function,
};

/**
 * 心跳函数
 */
void my_heartbeat_function(const void* user_data) {

    JSONObject jsonObject = json_create_object();
    json_object_add_member(&jsonObject,"action",json_create_string("notify"));
    json_object_add_member(&jsonObject,"command",json_create_string("1006"));
    json_object_add_member(&jsonObject, "device_id", json_create_string(config_data.device_id));
    json_object_add_member(&jsonObject, "sequence", json_create_number(get_next_sequence()));
    char *message = json_stringify(&jsonObject);

    // 给服务器发送信息
    mcp_send_message(message);
    LOG_DEBUG(">>>>>> Sent heartbeat data");
    json_free(&jsonObject);
    free(message);
}

//========================== 设备信息上传定时器 ===========================
static void my_device_info_update(const void* user_data);
comm_timer_t* timer_dis=NULL;
timer_config_t timer_config_dis = {
    .enabled = false,
    .interval_sec = 3,  // 3秒间隔
    .user_func = my_device_info_update,
};

/**
 * 设备信息上传时会跑这个
 * 先从上层获得json字符信息
 * 加上头信息后再发送
 */
void my_device_info_update(const void* user_data) {
    // 上层是否已定义了回调
    if (!config_data.on_get_device_info) {
        return;
    }
    const char* message = config_data.on_get_device_info(user_data);
    if (!message) {
        LOG_ERROR("== %s", emap_get(EMPTY_STRING)->desc);
        return;
    }

    char *local_message = malloc(strlen(message) + 1);
    strcpy(local_message, message);
    JSONObject parsed = json_parse(local_message);

    if (!&parsed || json_is_null(&parsed) || !json_is_object(&parsed)) {
        LOG_ERROR("== %s", emap_get(INVALID_JSON)->desc);
    }
    // 加入文件头和其它信息
    json_object_add_member(&parsed,"action",json_create_string("notify"));
    json_object_add_member(&parsed,"command",json_create_string("1015"));
    json_object_add_member(&parsed,"device_id",json_create_string(config_data.device_id));
    json_object_add_member(&parsed,"sequence",json_create_number(get_next_sequence()));
    char *json_message = json_stringify(&parsed);

    // 给服务器发送信息
    mcp_send_message(json_message);
    LOG_DEBUG(">>>>>> Sent device status data");
    // 释放资源
    json_free(&parsed);
    free(json_message);
    free(local_message);
}
//========================= 定位信息上传定时器 ===========================
static void my_position_info_update(const void* user_data);
comm_timer_t* timer_pos=NULL;
timer_config_t timer_config_pos = {
    .enabled = false,
    .interval_sec = 3,  // 3秒间隔
    .user_func = my_position_info_update,
};
/**
 * 定位信息上传时会跑这个
 * 先从上层获得json字符信息
 * 加上头信息后再发送
 */
void my_position_info_update(const void* user_data) {
    // 上层是否已定义了回调
    if (!config_data.on_get_position) {
        return;
    }
    const char* message = config_data.on_get_position(user_data);
    if (!message) {
        LOG_ERROR("== %s", emap_get(EMPTY_STRING)->desc);
        return;
    }

    char *local_message = malloc(strlen(message) + 1);
    strcpy(local_message, message);
    JSONObject parsed = json_parse(local_message);

    if (!&parsed || json_is_null(&parsed) || !json_is_object(&parsed)) {
        LOG_ERROR("== %s", emap_get(INVALID_JSON)->desc);
    }
    // 加入文件头和其它信息
    json_object_add_member(&parsed,"action",json_create_string("notify"));
    json_object_add_member(&parsed,"command",json_create_string("1010"));
    json_object_add_member(&parsed,"device_id",json_create_string(config_data.device_id));
    json_object_add_member(&parsed,"sequence",json_create_number(get_next_sequence()));
    char *json_message = json_stringify(&parsed);

    // 给服务器发送信息
    mcp_send_message(json_message);
    LOG_DEBUG(">>>>>> Sent position data");
    // 释放资源
    json_free(&parsed);
    free(json_message);
    free(local_message);
}

/**
 * 跨平台延时函数
 * @param sec 秒
 */
void mcp_cross_sleep(unsigned long sec) {
#ifdef _WIN32
    Sleep(sec * 1000);  // Windows 使用毫秒
#else
    struct timespec req = {
        .tv_sec = sec,
        .tv_nsec = 0
    };
    nanosleep(&req, NULL);  // Linux 使用纳秒
#endif
}

/**
 * 设置回调函数
 */
void set_on_register_success(const on_register_success callback) {
    config_data.on_register_success = callback;
}

void set_on_register_failure(const on_register_failure callback) {
    config_data.on_register_failure = callback;
}
void set_on_unregister(const on_unregister callback) {
    config_data.on_unregister = callback;
}
void set_on_cmd_success(const on_cmd_success callback) {
    config_data.on_cmd_success = callback;
}

void set_on_cmd_timeout(const on_cmd_timeout callback) {
    config_data.on_cmd_timeout = callback;
}

void set_on_async_response(const on_async_response callback) {
    config_data.on_async_response = callback;
}

void set_on_connection_status(const on_connection_status callback) {
    config_data.on_connection_status = callback;
}

void set_on_get_device_info(const on_get_device_info callback) {
    config_data.on_get_device_info = callback;
}
void set_on_get_position(const on_get_position callback) {
    config_data.on_get_position = callback;
}
void set_on_server_time(const on_server_time callback) {
    config_data.on_server_time = callback;
}

/**
 * 发送消息
 * @param json_message
 * @return
 */
int mcp_send_message(const char* json_message) {
    if (!json_message) {
        LOG_ERROR("Message is NULL");
        return;
    }

    char *local_message = malloc(strlen(json_message) + 1);
    strcpy(local_message, json_message);

    // 解析JSON消息
    JSONObject parsed = json_parse(local_message);
    // 无效的 json 字符串
    if (!&parsed || json_is_null(&parsed)) {
        // 不是有效的 JSON 字符串
        LOG_ERROR("== %s", emap_get(INVALID_JSON)->desc);
        return (int)INVALID_JSON;
    }
    //{action: n, sequence: nnnnn}
    if (json_is_object(&parsed)) {
        const CommandInfo* command_info = NULL;
        // 检查 action
        const char* action = json_get_string_key(&parsed, "action");
        if (!action || (strcmp(action, "request") != 0 && strcmp(action, "response") != 0 && strcmp(action, "notify") != 0)) {
            LOG_ERROR("== %s", emap_get(JSON_INVALID_ACTION)->desc);
            return (int)JSON_INVALID_ACTION;
        }

        /*JSONObject* action_value = json_get_object(&parsed, "action");
        if (!action_value || json_is_null(action_value)) {
            LOG_ERROR("== %s", emap_get(JSON_NOT_ACTION)->desc);
            return (int)JSON_NOT_ACTION;
        }
        if (json_is_string(action_value)) {
            // 不存在的指令
            const char* s_action_value = json_get_string(action_value);
            if (strcmp(s_action_value, "request") != 0 && strcmp(s_action_value, "response") != 0 && strcmp(s_action_value, "notify") != 0) {
                LOG_ERROR("== %s", emap_get(JSON_INVALID_ACTION)->desc);
                return (int)JSON_INVALID_ACTION;
            }
        }*/
        // 检查 command
        int i_command = json_get_int_key(&parsed, "command");
        if (i_command == 0) {
            const char*  command = json_get_string_key(&parsed, "command");
            if (!command) {
                LOG_ERROR("== %s", emap_get(JSON_NOT_COMMAND)->desc);
                return (int)JSON_NOT_COMMAND;
            }
            char* endptr;
            i_command = (int)strtol(command, &endptr, 10);
            // 检查转换是否成功
            if (*endptr != '\0') {
                LOG_ERROR("== %s", emap_get(JSON_NOT_COMMAND)->desc);
                return (int)JSON_NOT_COMMAND;
            }
            command_info = cmap_get(i_command);
        }
        if (command_info == NULL){
            LOG_ERROR("== %s", emap_get(JSON_INVALID_COMMAND)->desc);
            return (int)JSON_INVALID_COMMAND;
        }
        /*
        JSONObject* command_value = json_get_object(&parsed, "command");
        if (!command_value || json_is_null(command_value)) {
            LOG_ERROR("== %s", emap_get(JSON_NOT_COMMAND)->desc);
            return (int)JSON_NOT_COMMAND;
        }
        if (json_is_number(command_value)) {
            // 不存在的指令
            const int i_command_value = json_get_int(command_value);
            command_info = cmap_get(i_command_value);
            if (command_info == NULL){
                LOG_ERROR("== %s", emap_get(JSON_INVALID_COMMAND)->desc);
                return (int)JSON_INVALID_COMMAND;
            }
        } if (json_is_string(command_value)) {

        }*/

        // 检查 sequence
        JSONObject* sequence_value = json_get_object(&parsed, "sequence");
        if (!sequence_value || json_is_null(sequence_value)) {
            LOG_ERROR("== %s", emap_get(JSON_NOT_SEQUENCE)->desc);
            return (int)JSON_NOT_SEQUENCE;
        }

        // 发向服务端
        uint16_t packet_length;
        uint8_t packet[MAX_PACKET_SIZE];
        const uint16_t sequence = get_next_sequence();
        int result = create_packet(command_info->protocol, config_data.version, local_message, sequence,
            config_data.encrypt,0, 0, packet, &packet_length);
        if (result == 0) {
            static_push_data(packet, packet_length, sequence);
        } else {
            LOG_ERROR("Failed to create data packet: %d", result);
        }
        // 这里要释放内存
        // free_packet(packet);
    }
    // 释放资源
    json_free(&parsed);
    free(local_message);
    return 0;
}

// 重发管理器回调函数
static void on_retry_failed_callback(uint16_t sequence, int retry_count) {
    LOG_WARN("Message retry failed: sequence=%d, retry_count=%d", sequence, retry_count);
}

static void on_message_timeout_callback(uint16_t sequence) {
    LOG_ERROR("Message timeout: sequence=%d", sequence);
}

/**
 * 连接状态回调
 * 1、连接成功后，马上注册
 */
void status_handler(bool connected, const char* reason) {
    if (connected) {
        config_data.is_connected = true;
        if (config_data.on_connection_status) {
            config_data.on_connection_status(1, "success");
        }
        LOG_INFO("== OK Connected: %s", reason);

        // 连接成功后发送设备注册信息
        mcp_register();

    } else {
        config_data.is_connected = false;
        if (config_data.on_connection_status) {
            config_data.on_connection_status(0, reason);
        }
        LOG_INFO("== ERR Disconnected: %s", reason);

        // 停止心跳
        comm_timer_stop(timer_heartbeat);
    }
}

/**
 * 通用数据接收处理，处理完转队列
 * 1、由TCP或UDP接收到的数据流先到这个方法
 * 2、直接回复 0x80
 * 3、加入消息处理的队列
 */
static void static_recv_handler(uint8_t* data, uint16_t length, const char* from_ip,int from_port, connection_type_t connection_type) {
    CustomPacket packet;
    int ret = parse_packet(data, length, &packet);
    if (ret != 0) {
        LOG_ERROR("Failed to parse packet: %d", ret);
        free_packet(&packet);
        return;
    }
    // LOG_DEBUG("<<<<<< Data header: protocol=0x%02X, version=0x%02X, sequence=0x%04X", packet.protocol, packet.version, packet.sequence);
    // 同步响应，停止重发机制
    if (packet.protocol == 0x80) {
        mcp_retry_manager_handle_response(&retry_manager, packet.sequence);
        free_packet(&packet);
        return;
    }
    {
        // 立即响应0x80
        uint16_t packet_length;
        uint8_t packet0x80[MAX_PACKET_SIZE];
        int result = create_packet(0x80,config_data.version, NULL, packet.sequence, config_data.encrypt,
            0, 0,packet0x80, &packet_length);
        if (result == 0) {
            // 此处不需要重发
            mcp_net_send(&net_mgr, packet0x80, packet_length);
        }
    }

    uint8_t encrypt;
    uint8_t resp_protocol;
    uint16_t resp_sequence;
    char* message;

    // 解析数据包
    ret = parse_packet_data(packet.data, packet.data_length, &encrypt, &resp_protocol, &resp_sequence, &message);
    // LOG_DEBUG("数据包解码结果: %d\n", ret);
    if (ret == 0) {
        LOG_DEBUG("<<<<<< Packet Header: encrypt=%d, resp_protocol=0x%02X, resp_sequence=%d, message=%s\n",
               encrypt, resp_protocol, resp_sequence, message);
    }else {
        LOG_ERROR("<<<<<< Packet decoding error: %d\n", ret);
    }
    // LOG_DEBUG("<<<<<< Receive content: message=%s, protocol=0x%02X, sequence=%d",local_message, response_protocol, response_sequence);
    // 业务处理
    event_recv_msg(message,resp_protocol,resp_sequence);

    free(message);
    free_packet(&packet);



    // 将数据包加入处理器队列
    /*if (packet_processor && packet_processor_add_packet(packet_processor, &packet) != 0) {
        LOG_ERROR("Failed to add packet to processor, dropping it");
    }*/

    // free_packet(&packet);
}

/**
 * TCP接收回调
 */
void tcp_recv_handler(uint8_t* data, uint16_t length) {
    LOG_DEBUG("<<<<<< TCP Received: %d bytes", length);
    static_recv_handler(data, length, NULL, 0, CONNECTION_TYPE_TCP);
}

/**
 * UDP接收回调
 */
void udp_recv_handler(uint8_t* data, uint16_t length, const char* from_ip, int from_port) {
    LOG_DEBUG("UDP Received %d bytes from %s:%d", length, from_ip, from_port);
    static_recv_handler(data, length, from_ip, from_port, CONNECTION_TYPE_UDP);
}

/**
 * 接收消息处理
 * 从队列取出来的数据处理再反馈给上层
 */
void event_recv_msg(const char* message, uint8_t response_protocol, uint16_t response_sequence) {
    if (!message) {
        LOG_ERROR("Message is NULL");
        return;
    }
    char *local_message = malloc(strlen(message) + 1);
    strcpy(local_message, message);

    // 设置心跳数据
    strcpy(heartbeat_data.device_id, config_data.device_id);
    heartbeat_data.sequence = 0;

    // 解析JSON消息
    JSONObject parsed = json_parse(local_message);
    //===================== 注册(成功/失败)处理==================================
    if (response_protocol == 0x01) {
        if (json_is_object(&parsed)) {
            JSONObject* result_value = json_get_object(&parsed, "result");
            if (result_value && json_is_number(result_value)) {
                //===================== 注册成功处理==================================
                if (json_get_number(result_value) == 0) {
                    // 注册成功，开启心跳
                    //============================= 开启心跳 ===================================
                    bool enabled = false;
                    int interval = 0;
                    JSONObject* heartbeat_value = json_get_object(&parsed, "heartbeat");
                    if (heartbeat_value && json_is_object(heartbeat_value)){
                        enabled = json_get_boolean_key(heartbeat_value, "enabled");
                        interval = json_get_int_key(heartbeat_value, "interval");
                        if (interval == 0) interval = 20;
                    }
                    comm_timer_destroy(timer_heartbeat);
                    if (enabled) {
                        timer_config_heartbeat.interval_sec = interval;
                        timer_heartbeat = comm_timer_create(&timer_config_heartbeat);
                        comm_timer_start(timer_heartbeat);
                        LOG_INFO("== Device registered successfully, Start the heartbeat service");
                    }
                    //============================= 是否订阅设备信息=============================
                    enabled = false;
                    interval = 0;
                    JSONObject* dis_value = json_get_object(&parsed, "device_info_subscribe");
                    if (dis_value && json_is_object(dis_value)){
                        enabled = json_get_boolean_key(dis_value, "enabled");
                        interval = json_get_int_key(dis_value, "interval");
                        if (interval == 0) interval = 30;
                    }
                    comm_timer_destroy(timer_dis);
                    timer_config_dis.enabled = enabled;
                    if (enabled){
                        timer_config_dis.interval_sec = interval;
                        timer_dis = comm_timer_create(&timer_config_dis);
                        comm_timer_start(timer_dis);
                        LOG_INFO("== Device registered successfully, Start the device information reporting service");
                    }

                    //============================= 是否订阅定位信息 =============================
                    enabled = false;
                    interval = 0;
                    JSONObject* pos_value = json_get_object(&parsed, "position_subscribe");
                    if (pos_value && json_is_object(pos_value)){
                        enabled = json_get_boolean_key(pos_value, "enabled");
                        interval = json_get_int_key(pos_value, "interval");
                        if (interval == 0) interval = 30;
                    }
                    comm_timer_destroy(timer_pos);
                    timer_config_pos.enabled = enabled;
                    if (enabled) {
                        timer_config_pos.interval_sec = interval;
                        timer_dis = comm_timer_create(&timer_config_pos);
                        comm_timer_start(timer_pos);
                        LOG_INFO("== Device registered successfully, Start the position reporting service");
                    }

                    //============================= 返回给上层回调 =============================
                    if (config_data.on_register_success) {
                        config_data.on_register_success(local_message);
                    }
                }
                //===================== 注册失败处理==================================
                else {
                    LOG_ERROR("== Device registration failed");
                    // 停止定时器
                    comm_timer_stop(timer_heartbeat);
                    comm_timer_stop(timer_dis);
                    comm_timer_stop(timer_pos);

                    if (config_data.on_register_failure) {
                        config_data.on_register_failure(local_message);
                    }
                }
            }
        }
    }
    //===================== 注册注销处理==================================
    else if (response_protocol == 0x03) {

        LOG_INFO("== Device unregistered, heartbeat stopped");
        // 停止定时器
        comm_timer_stop(timer_heartbeat);
        comm_timer_stop(timer_dis);
        comm_timer_stop(timer_pos);

        // 回调
        if (config_data.on_unregister) {
            config_data.on_unregister(local_message);
        }
    }
    //===================== 服务器时间============================================
    else if (response_protocol == 0x08) {
        JSONObject jsonObject = json_create_object();
        const char* utc_time =  json_get_string_key(&parsed, "utc_time");
        json_object_add_member(&jsonObject, "utc_time", json_create_string(utc_time));
        char* json_message =  json_stringify(&jsonObject);
        if (!is_string_empty(utc_time)) {
            if (config_data.on_server_time) {
                config_data.on_server_time(json_message);
            }
        }
        free(json_message);
        json_free(&jsonObject);
    }

    else {
        // 其它返回上层
        if (config_data.on_async_response) {
            config_data.on_async_response(local_message);
        }
    }
    Sleep(100);
    // 调用相应的回调函数
    // 这里可以根据不同的协议号调用不同的回调
    free(local_message);
    json_free(&parsed);
}

/**
 * 发送 报警
 * @param alarm_message
 * @return
 */
int mcp_alarm(const char* alarm_message) {
    if (is_string_empty(alarm_message)) {
        LOG_ERROR("== %s", emap_get(INVALID_JSON)->desc);
        return (int)INVALID_JSON;
    }

    char *local_message = malloc(strlen(alarm_message) + 1);
    strcpy(local_message, alarm_message);

    // 解析JSON消息
    JSONObject parsed = json_parse(alarm_message);
    if (!&parsed || json_is_null(&parsed)) {
        // 不是有效的 JSON 字符串
        LOG_ERROR("== %s", emap_get(INVALID_JSON)->desc);
        return (int)INVALID_JSON;
    }
    // 发向服务端
    uint16_t packet_length;
    uint8_t packet[MAX_PACKET_SIZE];
    uint16_t sequence = get_next_sequence();
    const CommandInfo* command_info = cmap_get(1012);
    int result = create_packet(command_info->protocol, config_data.version, alarm_message, sequence,
        config_data.encrypt,0, 0, packet, &packet_length);
    if (result == 0) {
        static_push_data(packet,packet_length,sequence);

    } else {
        LOG_ERROR("Failed to create data packet: %d", result);
    }

    LOG_DEBUG(">>>>>> Sent alarm data");
    json_free(&parsed);
    free(local_message);
    return 0;
}
/**
 * 注册
 * 检测是否已初始化，是否已连接服务器
 * @return
 */
int mcp_register() {
    if (!&net_mgr || !&net_mgr.heartbeat_running || !mcp_net_is_connected(&net_mgr)) {
        LOG_ERROR("== Network is failure");
        return  -1;
    }
    JSONObject jsonObject = json_create_object();
    json_object_add_member(&jsonObject, "device_id", json_create_string(config_data.device_id));
    json_object_add_member(&jsonObject, "name", json_create_string(config_data.name));
    json_object_add_member(&jsonObject, "expire", json_create_number(3600));
    json_object_add_member(&jsonObject, "is_camera", json_create_boolean(0));
    char *message = json_stringify(&jsonObject);

    uint16_t packet_length;
    uint8_t packet[MAX_PACKET_SIZE];
    uint16_t sequence = get_next_sequence();
    const CommandInfo* command_info = cmap_get(1001);
    int result = create_packet(command_info->protocol, config_data.version, message, sequence, config_data.encrypt,
                              0, 0, packet, &packet_length);
    if (result == 0) {
        static_push_data(packet,packet_length,sequence);
    } else {
        LOG_ERROR(">>>>> Create registration packet error: %d", result);
    }
    LOG_DEBUG(">>>>>> Sent register data");
    free(message);
    return 0;
}

/**
 * 注销
 * @return
 */
int mcp_unregister() {
    if (!&net_mgr || !&net_mgr.heartbeat_running || !mcp_net_is_connected(&net_mgr)) {
        LOG_ERROR("== Network is failure");
        return  -1;
    }

    JSONObject jsonObject = json_create_object();
    json_object_add_member(&jsonObject, "device_id", json_create_string(config_data.device_id));
    char *message = json_stringify(&jsonObject);

    uint16_t packet_length;
    uint8_t packet[MAX_PACKET_SIZE];

    uint16_t sequence = get_next_sequence();
    const CommandInfo* command_info = cmap_get(1003);
    int result = create_packet(command_info->protocol, config_data.version, message, sequence, config_data.encrypt,
                              0, 0, packet, &packet_length);
    if (result == 0) {
        static_push_data(packet,packet_length,sequence);
    } else {
        LOG_ERROR(">>>>> Create packet error: %d", result);
    }
    LOG_DEBUG(">>>>>> Sent unregister data");

    free(message);
    json_free(&jsonObject);
    return 0;
}

/**
 * 请求服务器时间
 * @return
 */
int mcp_request_time() {
    JSONObject jsonObject = json_create_object();
    json_object_add_member(&jsonObject, "device_id", json_create_string(config_data.device_id));
    char *message = json_stringify(&jsonObject);

    uint16_t packet_length;
    uint8_t packet[MAX_PACKET_SIZE];

    const CommandInfo* command_info = cmap_get(1008);
    const uint16_t sequence = get_next_sequence();
    int result = create_packet(command_info->protocol, config_data.version, message, sequence, config_data.encrypt,
                              0, 0, packet, &packet_length);
    if (result == 0) {
        static_push_data(packet,packet_length,sequence);
    } else {
        LOG_ERROR(">>>>> Create packet error: %d", result);
    }
    LOG_DEBUG(">>>>>> Send command to request the server time");
    return 0;
}
/**
 * 初始化MCP服务
 */
int mcp_init(const char* ip, const int port, const char* device_id, const int interval, const int socket_type) {
    // 设置随机种子
    srand((unsigned int)time(NULL));

    // 如果服务正在运行，先停止
    if (atomic_load(&config_data.is_running)) {
        LOG_INFO("== Stop mcp");
        mcp_stop();
    }
    // 命令行初始化
    cmap_init();
    LOG_INFO("== Command map init");
    // 异常描述初始化
    emap_init();
    LOG_INFO("== Exception map init");

    // 复制配置参数
    strncpy(config_data.server_ip, ip, sizeof(config_data.server_ip) - 1);
    config_data.server_port = port;
    strncpy(config_data.device_id, device_id, sizeof(config_data.device_id) - 1);
    config_data.interval = interval;

    // 设置socket类型
    if (socket_type == 1) {
        config_data.socket_type = CONNECTION_TYPE_TCP;
    } else if (socket_type == 2) {
        config_data.socket_type = CONNECTION_TYPE_UDP;
    }

    LOG_INFO("== MCP service initialized: ip=%s, port=%d, device_id=%s, interval=%d, type=%d", ip, port, device_id, interval, socket_type);

    return 0;
}

void mcp_destroy() {
    comm_timer_destroy(timer_dis);
    comm_timer_destroy(timer_pos);

    cmap_free();
    emap_free();
}

/**
 * 启动MCP服务
 */
int mcp_start() {
    if (strlen(config_data.device_id) == 0) {
        LOG_ERROR("Device id is empty, Please call init() first");
        return -1;
    }

    if (atomic_load(&config_data.is_running)) {
        LOG_ERROR("Service is already running");
        return -2;
    }
    // 初始化消息重发管理器
    mcp_retry_manager_init(&retry_manager, 100);
    mcp_retry_manager_set_callbacks(&retry_manager,on_retry_failed_callback,on_message_timeout_callback);

    // 初始化网络管理器
    int ret = mcp_net_init(&net_mgr, tcp_recv_handler, udp_recv_handler, status_handler);
    if (ret != 0) {
        LOG_ERROR("Failed to init network manager: %d", ret);
        packet_processor_destroy(packet_processor);
        packet_processor = NULL;
        return -4;
    }

    // 连接网络
    int conn_ret = -100;
    if (config_data.socket_type == CONNECTION_TYPE_TCP) {
        LOG_INFO("Connecting via TCP to %s:%d", config_data.server_ip, config_data.server_port);
        conn_ret = mcp_net_connect_tcp(&net_mgr, config_data.server_ip, config_data.server_port);
    } else if (config_data.socket_type == CONNECTION_TYPE_UDP) {
        LOG_INFO("Connecting via UDP to %s:%d", config_data.server_ip, config_data.server_port);
        conn_ret = mcp_net_connect_udp(&net_mgr, config_data.server_ip, config_data.server_port);
    } else {
        LOG_ERROR("Invalid connection type: %d", config_data.socket_type);
        packet_processor_destroy(packet_processor);
        packet_processor = NULL;
        return -5;
    }

    if (conn_ret != 0) {
        LOG_ERROR("Network connection failed: %d", conn_ret);
        packet_processor_destroy(packet_processor);
        packet_processor = NULL;
        return -6;
    }

    // 设置运行状态
    atomic_store(&config_data.is_running, true);
    LOG_INFO("MCP service started successfully");

    return 0;
}

/**
 * 停止MCP服务
 */
int mcp_stop() {
    if (!atomic_load(&config_data.is_running)) {
        LOG_WARN("Service not running");
        return 0;
    }

    LOG_INFO("Stopping MCP service...");
    atomic_store(&config_data.is_running, false);

    // 清理资源
    mcp_retry_manager_cleanup(&retry_manager);

    // 停止网络连接
    mcp_net_close(&net_mgr);
    mcp_net_cleanup(&net_mgr);

    // 销毁数据包处理器
    /*if (packet_processor) {
        packet_processor_destroy(packet_processor);
        packet_processor = NULL;
    }*/

    atomic_store(&config_data.is_connected, false);
    LOG_INFO("MCP service stopped successfully");

    return 0;
}

/**
 * 检查服务是否运行
 */
bool mcp_is_running(void) {
    return atomic_load(&config_data.is_running);
}

/**
 * 检查是否已连接
 */
bool mcp_is_connected(void) {
    return atomic_load(&config_data.is_connected);
}

/**
 * 信息重发
 * @param sequence      序号，唯一值每个指令的序号都不同
 * @param packet_data   数据包
 * @param packet_length  数据包长度
 * @param user_data    用户数据
 */
static void static_resend_message(uint16_t sequence, uint8_t* packet_data,uint16_t packet_length, void* user_data) {
    // 从重发管理器中获取消息数据并重新发送，也可以做更复杂的数据管理
    LOG_INFO("== Resending message: sequence=%d", sequence);
    mcp_net_send(&net_mgr, packet_data, packet_length);
}

/**
 * 当服务端发来 0x80后，表示此数据包发送成功
 * @param sequence
 * @param user_data
 */
static void static_send_success(uint16_t sequence, void* user_data) {
    LOG_INFO("== Message confirmed: sequence=%d", sequence);
}

/**
 * 发送到 服务器端，并加入到重发机制里，如果没有收到 0x80 响则重发
 * @param data
 * @param length
 * @param sequence
 */
void static_push_data(const uint8_t* data, uint16_t length, uint16_t sequence){
    int ret = mcp_net_send(&net_mgr, data, length);
    // 启动重机制，直到收到 0x80
    // 添加到重发管理器
    if (ret == 0) {
        ret = mcp_retry_manager_add_message(&retry_manager, sequence, data, length,
                                    static_resend_message,
                                    static_send_success,
                                    NULL);
        if (ret != 0) {
            LOG_ERROR("== !Retry add exception");
        }
    }
}